package org.jeecg.modules.mp.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.JwidModel;
import org.jeecg.config.mybatis.TenantContext;
import org.jeecg.modules.mp.entity.JwMsgTemplate;
import org.jeecg.modules.mp.mapper.JwMsgTemplateMapper;
import org.jeecg.modules.mp.service.IJwMsgTemplateService;
import org.jeecg.modules.mp.service.IJwWebJwidService;
import org.jeewx.api.core.exception.WexinReqException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description: 微信消息模板
 * @Author: jeecg-boot
 * @Date:   2022-04-12
 * @Version: V1.0
 */
@Service
public class JwMsgTemplateServiceImpl extends ServiceImpl<JwMsgTemplateMapper, JwMsgTemplate> implements IJwMsgTemplateService {

    @Autowired
    private IJwWebJwidService jwWebJwidService;
    @Autowired
    private ISysBaseAPI baseAPI;

    @Override
    public Result<?> synAdd(JwMsgTemplate jwMsgTemplate) {

        String tenant = TenantContext.getTenant();
        JSONObject param = new JSONObject();
        param.put("tenantId",tenant);
        JwidModel jwModel = baseAPI.getJwId(param);

        try {
           String templateLsStr = jwWebJwidService.getTemplateList(jwModel.getAccessToken());
           JSONObject temObj = (JSONObject) JSONObject.parse(templateLsStr);
           if(null != temObj){
               JSONArray templateList = temObj.getJSONArray("template_list");
               for (Object o : templateList) {
                   JSONObject tem=(JSONObject)o;
                   JwMsgTemplate msgTemplate=new JwMsgTemplate();
                   msgTemplate.setTemplateId(tem.getString("template_id"));
                   msgTemplate.setTitle(tem.getString("title"));
                   msgTemplate.setPrimaryIndustry(tem.getString("primary_industry"));
                   msgTemplate.setDeputyIndustry(tem.getString("deputy_industry"));
                   msgTemplate.setContent(tem.getString("content"));
                   msgTemplate.setExample(tem.getString("example"));
                   msgTemplate.setJwid(jwModel.getId());
                   msgTemplate.setStatus("1");
                   baseMapper.insert(msgTemplate);
               }
               return Result.OK("同步成功");
           }
        } catch (WexinReqException e) {
            e.printStackTrace();
            return Result.error("同步异常："+e.getMessage());
        }

        return Result.error("同步异常");
    }
}
